package top.kaoshanji.p2ch10b;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.u1constant.FileConstant;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

/**
 * 代码清单-p2ch10b-333页a：Externalizable接口的使用示例
 * author kaoshanji
 * ^_^
 * create time 2025/2/3 13:13
 */
public class ExternalizableUser implements Externalizable {

    private static final Logger logger = LogManager.getLogger(ExternalizableUser.class);

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        logger.info("...代码清单-p2ch10b-333页a：Externalizable接口的使用示例...");

        ExternalizableUser user = new ExternalizableUser("Alex", "alex@example.org");

        String filePath = FileConstant.LOCAL_ROOT_PATH.concat("p2ch10b333页a\\e_user.bin");

        SerializationUtils.write(user, filePath);

        user = (ExternalizableUser)SerializationUtils.read(filePath);

        logger.info("...用户的email的值：{}...", user.getEmail());

    }

    private String name;
    private String email;

    public ExternalizableUser() {}

    public ExternalizableUser(String name, String email) {
        this.name = name;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public String getEmail() {
        return email;
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeUTF(getName());
        out.writeUTF(getEmail());
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        name = in.readUTF();
        email = in.readUTF();
    }

}
